using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Newtonsoft.Json;

namespace 电商价格监控器
{
    /// <summary>
    /// 商品价格监控核心类
    /// </summary>
    public class ProductMonitor
    {
        /// <summary>
        /// 监控的商品信息
        /// </summary>
        public class MonitoredProduct
        {
            public string SkuId { get; set; }
            public string Url { get; set; }
            public string Title { get; set; }
            public string CurrentPrice { get; set; }
            public string TargetPrice { get; set; }
            public string Stock { get; set; }
            public DateTime LastCheckTime { get; set; }
            public List<PriceHistory> History { get; set; } = new List<PriceHistory>();
        }

        /// <summary>
        /// 价格历史记录
        /// </summary>
        public class PriceHistory
        {
            public DateTime Time { get; set; }
            public string Price { get; set; }
            public string Stock { get; set; }
        }

        /// <summary>
        /// 监控配置
        /// </summary>
        public class MonitorConfig
        {
            /// <summary>
            /// 检查间隔（分钟）
            /// </summary>
            public int CheckIntervalMinutes { get; set; } = 30;

            /// <summary>
            /// 是否启用邮件通知
            /// </summary>
            public bool EnableEmailNotification { get; set; } = false;

            /// <summary>
            /// 邮件服务器配置
            /// </summary>
            public EmailConfig Email { get; set; } = new EmailConfig();

            /// <summary>
            /// 是否启用微信通知（通过企业微信机器人）
            /// </summary>
            public bool EnableWeChatNotification { get; set; } = false;

            /// <summary>
            /// 企业微信机器人 Webhook URL
            /// </summary>
            public string WeChatWebhookUrl { get; set; } = "";

            /// <summary>
            /// 是否启用系统消息框通知
            /// </summary>
            public bool EnableMessageBoxNotification { get; set; } = true;
        }

        /// <summary>
        /// 邮件配置
        /// </summary>
        public class EmailConfig
        {
            public string SmtpServer { get; set; } = "smtp.gmail.com";
            public int SmtpPort { get; set; } = 587;
            public string FromEmail { get; set; } = "";
            public string FromPassword { get; set; } = "";
            public string ToEmail { get; set; } = "";
            public bool EnableSsl { get; set; } = true;
        }

        private const string DataFileName = "monitor_data.json";
        private MonitoredProduct _product;
        private MonitorConfig _config;

        public MonitoredProduct Product => _product;
        public MonitorConfig Config => _config;

        public ProductMonitor()
        {
            _config = new MonitorConfig();
            LoadData();
        }

        /// <summary>
        /// 设置要监控的商品
        /// </summary>
        public void SetProduct(string skuId, string url, string title, string targetPrice)
        {
            _product = new MonitoredProduct
            {
                SkuId = skuId,
                Url = url,
                Title = title,
                TargetPrice = targetPrice,
                CurrentPrice = "N/A",
                Stock = "未知",
                LastCheckTime = DateTime.MinValue
            };
        }

        /// <summary>
        /// 更新商品价格和库存
        /// </summary>
        public PriceChangeResult UpdatePrice(string newPrice, string newStock)
        {
            if (_product == null)
                return new PriceChangeResult { Changed = false };

            string oldPrice = _product.CurrentPrice;
            string oldStock = _product.Stock;

            _product.CurrentPrice = newPrice;
            _product.Stock = newStock;
            _product.LastCheckTime = DateTime.Now;

            // 添加到历史记录
            _product.History.Add(new PriceHistory
            {
                Time = DateTime.Now,
                Price = newPrice,
                Stock = newStock
            });

            // 只保留最近100条记录
            if (_product.History.Count > 100)
            {
                _product.History.RemoveAt(0);
            }

            SaveData();

            // 判断是否有价格变化
            bool priceChanged = oldPrice != newPrice && oldPrice != "N/A";
            bool stockChanged = oldStock != newStock && oldStock != "未知";
            bool reachedTarget = false;

            if (!string.IsNullOrEmpty(_product.TargetPrice) && newPrice != "N/A")
            {
                try
                {
                    decimal current = ParsePrice(newPrice);
                    decimal target = ParsePrice(_product.TargetPrice);
                    reachedTarget = current <= target;
                }
                catch { }
            }

            return new PriceChangeResult
            {
                Changed = priceChanged || stockChanged,
                PriceChanged = priceChanged,
                StockChanged = stockChanged,
                ReachedTarget = reachedTarget,
                OldPrice = oldPrice,
                NewPrice = newPrice,
                OldStock = oldStock,
                NewStock = newStock
            };
        }

        /// <summary>
        /// 价格变化结果
        /// </summary>
        public class PriceChangeResult
        {
            public bool Changed { get; set; }
            public bool PriceChanged { get; set; }
            public bool StockChanged { get; set; }
            public bool ReachedTarget { get; set; }
            public string OldPrice { get; set; }
            public string NewPrice { get; set; }
            public string OldStock { get; set; }
            public string NewStock { get; set; }
        }

        /// <summary>
        /// 解析价格字符串为数字
        /// </summary>
        private decimal ParsePrice(string priceText)
        {
            if (string.IsNullOrEmpty(priceText))
                return 0;

            // 移除所有非数字字符（保留小数点）
            StringBuilder sb = new StringBuilder();
            foreach (char c in priceText)
            {
                if (char.IsDigit(c) || c == '.')
                    sb.Append(c);
            }

            if (decimal.TryParse(sb.ToString(), out decimal result))
                return result;

            return 0;
        }

        /// <summary>
        /// 保存数据到文件
        /// </summary>
        public void SaveData()
        {
            try
            {
                var data = new
                {
                    Product = _product,
                    Config = _config
                };

                string json = JsonConvert.SerializeObject(data, Formatting.Indented);
                File.WriteAllText(DataFileName, json, Encoding.UTF8);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"保存数据失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 从文件加载数据
        /// </summary>
        public void LoadData()
        {
            try
            {
                if (File.Exists(DataFileName))
                {
                    string json = File.ReadAllText(DataFileName, Encoding.UTF8);
                    var data = JsonConvert.DeserializeObject<dynamic>(json);
                    
                    if (data.Product != null)
                        _product = JsonConvert.DeserializeObject<MonitoredProduct>(data.Product.ToString());
                    
                    if (data.Config != null)
                        _config = JsonConvert.DeserializeObject<MonitorConfig>(data.Config.ToString());
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载数据失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取通知消息文本
        /// </summary>
        public string GetNotificationMessage(PriceChangeResult result)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine($"📦 商品: {_product.Title}");
            sb.AppendLine($"🔗 链接: {_product.Url}");
            sb.AppendLine();

            if (result.PriceChanged)
            {
                sb.AppendLine($"💰 价格变化:");
                sb.AppendLine($"   旧价格: {result.OldPrice}");
                sb.AppendLine($"   新价格: {result.NewPrice}");
            }

            if (result.StockChanged)
            {
                sb.AppendLine($"📊 库存变化:");
                sb.AppendLine($"   旧库存: {result.OldStock}");
                sb.AppendLine($"   新库存: {result.NewStock}");
            }

            if (result.ReachedTarget)
            {
                sb.AppendLine();
                sb.AppendLine($"🎯 已达到目标价格: {_product.TargetPrice}！");
            }

            sb.AppendLine();
            sb.AppendLine($"⏰ 检查时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");

            return sb.ToString();
        }
    }
}


